<template>
  <el-dialog title="驳回原因" top="15vh" :visible="dialogVisible" width="800px" :close-on-click-modal="false" :before-close="handleClose">
    <el-form ref="rejectRef" :model="rejuseFrom" label-width="80px" size="mini">
      <el-form-item v-if="formRoute !== 'examine'" label="驳回原因" prop="rejectReasonList">
        <el-select v-model="rejuseFrom.rejectReasonList" placeholder="请选择驳回原因" value-key="rejectReasonId" multiple filterable clearable>
          <el-option v-for="item in rejectReasonOption" :key="item.rejectReasonId" :label="item.rejectReason" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <!-- <el-input v-model="rejuseFrom.remarks" placeholder="备注" type="textarea" :rows="2" /> -->
        <div ref="editorRef" class="editor-wrapper" />
      </el-form-item>
      <div v-if="tipshow" class="tip">* 驳回备注最大字数为1000</div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" type="danger" icon="el-icon-circle-close" round @click="handleClose">取消</el-button>
      <el-button size="mini" type="success" icon="el-icon-circle-check" round :loading="rejectSavaLoad" @click="agreeToReject">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import WEditor from 'wangeditor'
import { reasonController, purchaseReject, complianceReject, rejectedComplianceApproval, rejectedProcurementApproval } from '@/api/coi/onlineTaskAPI/sku'
import bus from '@/utils/eventBus.js'
import { rejectFun } from '../js/requser.js'
export default {
  name: 'RejectApproval',
  data() {
    return {
      dialogVisible: false,
      rejuseFrom: {
        skuIds: [this.$route.params.id]
      },
      rejectReasonOption: [],
      editor: null,
      rejectSavaLoad: false,
      html: '',
      tipshow: false,
      formRoute: ''
    }
  },
  watch: {
    dialogVisible(v) {
      this.tipshow = false
      if (v && !this.editor) {
        this.$nextTick(() => {
          this.initEditor()
        })
      }
    }
  },
  mounted() {
    this.rejectOption()
    this.formRoute = this.$route.query.formRoute ? this.$route.query.formRoute : ''
  },
  methods: {
    // 弹窗关闭事件
    handleClose() {
      this.dialogVisible = false
    },
    getType() {
      if (this.$route.params.from === 'PurchaseApprovalList') return 1
      else if (this.$route.params.from === 'ComplianceApprovalList') return 2
      else null
    },
    agreeToReject() {
      this.$refs.rejectRef.validate(async (valid) => {
        if (valid) {
          if (this.formRoute !== 'examine') {
            try {
              this.rejectSavaLoad = true
              const dataList = JSON.parse(JSON.stringify(this.rejuseFrom))
              let param = {}
              if (this.$route.params.mainStatus !== '9020' && this.$route.params.mainStatus !== '9030') {
                if (dataList.remarks) dataList.rejectReasonList.push({ rejectReasonId: 0, rejectReason: dataList.remarks })
                delete dataList.remarks
              } else {
                const rejectIds = []
                this.rejuseFrom.rejectReasonList.forEach((item) => {
                  rejectIds.push(item.rejectReasonId)
                })
                param = {
                  processId: Number(this.$route.params.id),
                  rejectReason: this.rejuseFrom.remarks,
                  rejectReasonIds: rejectIds
                }
              }
              const type = this.getType()
              let res = null
              if (type === 1) res = this.$route.params.mainStatus === '9020' ? await rejectedProcurementApproval(param) : await purchaseReject(dataList)
              else if (type === 2) res = this.$route.params.mainStatus === '9030' ? await rejectedComplianceApproval(param) : await complianceReject(dataList)
              else return
              if (res.result) {
                this.$message({ type: 'success', message: '驳回审核成功！' })
                this.$refs.rejectRef.resetFields()
                this.editor.txt.html('')
                this.handleClose()
                bus.$emit('closeTag', this.$route)
              }
            } finally {
              this.rejectSavaLoad = false
            }
          } else {
            // console.log('文描上下架啊啊啊', this.rejuseFrom)
            try {
              const obj = {
                rejectReason: this.rejuseFrom.remarks,
                id: this.$route.params.id
              }
              const res = await rejectFun(obj)
              if (res.result) {
                this.$message({ type: 'success', message: '驳回审核成功！' })
                this.$refs.rejectRef.resetFields()
                this.editor.txt.html('')
                this.handleClose()
                bus.$emit('closeTag', this.$route)
              }
              // console.log('文描上下架啊啊啊', res)
            } catch (error) {
              console.log(error)
            } finally {
              this.rejectSavaLoad = false
            }
          }
        }
      })
    },
    // 获取审核的驳回原因
    async rejectOption() {
      const type = this.getType()
      if (type) {
        const res = await reasonController({ type, pageSize: 100 })
        if (res.result && res.result.data) {
          this.rejectReasonOption = res.result.data.map((item) => {
            return { rejectReasonId: item.id, rejectReason: item.reason }
          })
        }
      }
    },
    initEditor() {
      this.editor = new WEditor(this.$refs.editorRef)
      this.editor.config.height = 300 // 文本框的高度
      this.editor.config.placeholder = '请输入审核驳回备注' // 提示语
      this.editor.config.showFullScreen = false // 配置全屏
      this.editor.config.pasteFilterStyle = false // 关闭从其他网站粘贴过来的样式处理
      this.editor.config.uploadImgShowBase64 = false // base 64 存储图片
      this.editor.config.showLinkImg = false // 关闭通过图片地址添加图片
      // 配置菜单 可根据文档进行添加
      this.editor.config.menus = [
        // 'head', // 标题
        // 'bold', // 字体粗细
        // 'fontSize', // 字号
        // 'fontName', // 字体
        // 'italic', // 倾斜
        // 'underline', // 下划线
        // 'strikeThrough', // 删除线
        // 'indent', // 缩进
        // 'lineHeight', // 行高
        // 'foreColor', // 字体颜色
        // 'backColor', // 背景颜色
        // 'link',//链接
        // 'list', // 序列
        // 'todo', // 代办
        // 'justify', // 对齐
        // 'quote', // 引用
        // 'emoticon', // 表情
        // 'image', // 图片
        // 'video',//视频
        // 'table', // 表格
        // 'code',//插入代码
        // 'splitLine', // 分割线
        // 'undo', // 撤销
        // 'redo'// 恢复
      ]
      const _this = this
      this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        resultFiles.forEach(async (element) => {
          const formData = new FormData()
          formData.append('file', element)
          formData.append('skuId', _this.id)
          // const result = await uploadSkuContentResource(formData)
          // if (result.code === '0') {
          //   insertImgFn(result.result.resourceUrl)
          // }
        })
      }
      // 创建富文本编辑器
      this.editor.config.onchange = (html) => {
        if (this.editor.txt.text().length <= 1000) {
          this.html = html
          this.rejuseFrom.remarks = html
        } else {
          this.editor.txt.html(this.html)
          this.tipshow = true
        }
      }
      this.editor.config.zIndex = 2 // 配置富文本的权重 不然会覆盖其他组件
      this.editor.create()
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-select {
  width: 100%;
}
.tip {
  margin-left: 80px;
  color: #ff4949;
}
</style>
>
